package com.toogu.mazhangmen.util;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.bumptech.glide.Glide;
import com.toogu.mazhangmen.R;
import com.toogu.mazhangmen.bean.EquipmentsBean;
import com.toogu.mazhangmen.bean.QATypeBean;
import com.toogu.mazhangmen.ui.view.RadioGroupView;
import com.toogu.mazhangmen.ui.view.ReSpinner;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import jaygoo.widget.wlv.WaveLineView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class PopUtil {



    /**
     * 获取屏幕高度(px)
     */
    public static int getScreenHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }
    /**
     * 获取屏幕宽度(px)
     */
    public static int getScreenWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    public static int[] calculatePopWindowPos(final View anchorView, final View contentView) {
        final int windowPos[] = new int[2];
        final int anchorLoc[] = new int[2];
        // 获取锚点View在屏幕上的左上角坐标位置
        anchorView.getLocationOnScreen(anchorLoc);

        final int anchorHeight = anchorView.getHeight();//高度
        final int anchorWidth = anchorView.getWidth();//宽度
        // 获取屏幕的高宽
        final int screenHeight = getScreenHeight(anchorView.getContext());
        final int screenWidth = getScreenWidth(anchorView.getContext());

        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        // 计算contentView的高宽
        final int windowHeight = contentView.getMeasuredHeight();//View的高度
        final int windowWidth = contentView.getMeasuredWidth();//View的宽度
        // 判断需要向上弹出还是向下弹出显示
        final boolean isNeedShowUp = (screenHeight - anchorLoc[1] - anchorHeight < windowHeight);

        if (isNeedShowUp) {
            windowPos[0] =  anchorLoc[0]-windowWidth/2+anchorWidth/2;
            windowPos[1] = anchorLoc[1] - windowHeight;
        } else {
            windowPos[0] = anchorLoc[0]-windowWidth/2+anchorWidth/2;
            windowPos[1] = anchorLoc[1] + anchorHeight;
        }
        return windowPos;
    }

    public  void showWait(Activity activity) {
        DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    return true;
                } else {
                    return false;
                }
            }
        };
        final View view = LayoutInflater.from(activity).inflate(R.layout.item_wait, null);
        final AlertDialog.Builder normalDialog = new AlertDialog.Builder(activity);
        normalDialog.setView(view);
        normalDialog.setOnKeyListener(keylistener);
        normalDialog.setCancelable(false);
        activity.runOnUiThread(()->{
            AlertDialog dialog = normalDialog.show();
            dialog.getWindow().setLayout(UiUtil.dip2px(100), LinearLayout.LayoutParams.WRAP_CONTENT);
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    activity.runOnUiThread(() -> {
                        try {
                            if (activity != null && dialog.isShowing()) dialog.dismiss();
                        }catch (Exception e){

                        }
                        timer.cancel();
                    });
                }
            }, 1500);
        });
    }

    private static String doorId = null;
    private static String qaId = null;
    public static void showQACall(Activity activity, EquipmentsBean equipmentsBean, List<QATypeBean> qaTypeBeanList) {
        String[] qaName = new String[qaTypeBeanList.size()];
        for(int i=0;i<qaTypeBeanList.size();i++){
            qaName[i] = qaTypeBeanList.get(i).getText();
        }
        PopupWindow popupWindow = new PopupWindow(activity);
        LinearLayout layout = new LinearLayout(activity);
        final View rootView = LayoutInflater.from(activity).inflate(R.layout.item_qa_call, null, false);
        RadioGroupView radioGroupView = rootView.findViewById(R.id.RadioGroupView);
        ReSpinner reSpinner = rootView.findViewById(R.id.respinner);
        EditText editText = rootView.findViewById(R.id.editText);
        Button button = rootView.findViewById(R.id.button);
        layout.addView(rootView);
        layout.setPadding(UiUtil.dip2px(10),UiUtil.dip2px(10),UiUtil.dip2px(10),UiUtil.dip2px(10));
        layout.setBackgroundResource(R.drawable.bg_radius);
        popupWindow.setContentView(layout);

        //radioGroupView
        if(equipmentsBean.getDoor()!=null){
            String[] doorName = new String[]{equipmentsBean.getDoor().getName()};
            radioGroupView.setInit(doorName);
            radioGroupView.select(0);
        }
        if(equipmentsBean.getDoors()!=null){
            String[] doorName = new String[equipmentsBean.getDoors().size()];
            for(int i=0;i<equipmentsBean.getDoors().size();i++){
                doorName[i]=equipmentsBean.getDoors().get(i).getName();
            }
            radioGroupView.setInit(doorName);
            radioGroupView.select(0);
        }
        if(equipmentsBean.getDoor()!=null){
            doorId = equipmentsBean.getDoor().getId();
        }else{
            doorId = equipmentsBean.getDoors().get(0).getId();
        }

        radioGroupView.setOnCheckedChangeListener(new RadioGroupView.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(int situation) {
                if(equipmentsBean.getDoor()!=null){
                    doorId = equipmentsBean.getDoor().getId();
                }else{
                    doorId = equipmentsBean.getDoors().get(situation).getId();
                }
            }
        });

        //Respinner
        reSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                qaId = qaTypeBeanList.get(position).getValue()+"";
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(editText.getText().toString().equals("")){
                    Toast.makeText(activity,"原因不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                popupWindow.dismiss();
                NetWorkUtil.getNetWorkUtil().pushQAType(activity, doorId, qaId, editText.getText().toString(), new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        activity.runOnUiThread(()->Toast.makeText(activity,"失败:"+e.getMessage(),Toast.LENGTH_SHORT).show());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if(!response.isSuccessful()){
                            Log.d("pushQAType", "onResponse: "+response);
                           activity.runOnUiThread(()->Toast.makeText(activity,"失败"+response,Toast.LENGTH_SHORT).show());
                        }
                    }
                });
            }
        });

        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(activity, R.layout.view_spinner_item3, Arrays.asList(qaName));
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        reSpinner.setAdapter(arrayAdapter);

        //

        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                UiUtil.setBackgroundAlpha(activity,1f);
            }
        });
        UiUtil.setBackgroundAlpha(activity,0.5f);
        popupWindow.showAtLocation(activity.getWindow().getDecorView(), Gravity.CENTER,0,0);
    }



    public  void showPicture(Activity activity,String address) {
        PopupWindow popupWindow = new PopupWindow(activity);
        LinearLayout layout = new LinearLayout(activity);
        ImageView imageView = new ImageView(activity);
        layout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        layout.setBackgroundResource(R.drawable.bg_radius);
        layout.setPadding(UiUtil.dip2px(10),UiUtil.dip2px(10),UiUtil.dip2px(10),UiUtil.dip2px(10));
        layout.addView(imageView,new LinearLayout.LayoutParams(UiUtil.dip2px(500), ViewGroup.LayoutParams.WRAP_CONTENT));
        Glide.with(activity)
                .load(address)
                .fallback(R.drawable.ic_temp)
                .placeholder(R.drawable.ic_temp)
                .into(imageView);

        popupWindow.setContentView(layout);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                UiUtil.setBackgroundAlpha(activity,1f);
            }
        });
        UiUtil.setBackgroundAlpha(activity,0.5f);
        popupWindow.showAtLocation(activity.getWindow().getDecorView(), Gravity.CENTER,0,0);


    }

    //延迟一秒显示录音动画
    private static int DELAY = 500;
    public static void showTalk(Activity activity,MonitorUtil monitorUtil){
        final View rootView = LayoutInflater.from(activity).inflate(R.layout.item_talk, null, false);
        PopupWindow  popupWindow = new PopupWindow(rootView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        WaveLineView waveLineView = rootView.findViewById(R.id.waveLineView);
        Button button =rootView.findViewById(R.id.button);
        monitorUtil.openVoice();
        button.setText("按住说话");
        Handler delayHandler = new Handler();
        button.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        monitorUtil.openTalk();
                        delayHandler.postDelayed(() -> {
                            waveLineView.setVisibility(View.VISIBLE);
                            waveLineView.startAnim();
                            button.setText("松开收音");
                        }, DELAY);
                        return true;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_OUTSIDE:
                        monitorUtil.closeTalk();
                        waveLineView.stopAnim();
                        waveLineView.setVisibility(View.INVISIBLE);
                        button.setText("按住说话");
                        return true;
                }
                return false;
            }
        });
        popupWindow.setContentView(rootView);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                monitorUtil.closeTalk();
                monitorUtil.closeVoice();
                waveLineView.release();
                UiUtil.setBackgroundAlpha(activity,1f);
            }
        });
        UiUtil.setBackgroundAlpha(activity,0.5f);
        popupWindow.showAtLocation(activity.getWindow().getDecorView().getRootView(), Gravity.BOTTOM,0,0);

    }
}
